package com.tangpian.framework.web.controller;

import java.util.List;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.tangpian.framework.entity.Task;
import com.tangpian.framework.service.task.TaskService;

@Controller
@RequestMapping(value = "/task")
public class TaskController {

	@Autowired
	private TaskService taskService;
	
	@RequestMapping(method = RequestMethod.GET)
	public String list(ModelMap model) {
		List<Task> tasks = taskService.listAllTask();
		model.put("tasks", tasks);
		model.put("size",tasks.size());
		return "task/list";
	}

	@RequestMapping("{id}")
	public String showDetail(@PathVariable("id") String id, ModelMap model) {
		Task task = taskService.getTask(id);
		model.put("task", task);
		return "task/detail";
	}

	@RequestMapping(method = RequestMethod.GET, value = "create")
	public String showCreateForm(@ModelAttribute Task task) {
		return "task/form";
	}

	@RequestMapping(method = RequestMethod.POST, value = "create")
	public String createTask(@Valid @ModelAttribute("task") Task task, BindingResult result) {
		if (result.hasErrors()) {
			return "task/form";
		}
		taskService.createTask(task);
		return "redirect:/";
	}
}
